package com.njbw.user.init;

import com.alibaba.fastjson.JSON;
import com.njbw.user.designPattern.builderPattern.SkuDO;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 容器都加载完之后会去触发 ApplicationReadyEvent
 */
@Log4j2
@Component
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {

    Map<String, InitFunction> initFunctionMap = new HashMap<>();

    {
        initFunctionMap.put("预热 FastJson", this::initFastJson);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 服务器启动之后，所有想预热的东西想做的事都可以在这里做
        // 整个项目都启动之后
        System.out.println("服务启动完成！");
        // 预热 httpClient
        // 预热 Json
        // 预热一个线程池
        initFunctionMap.forEach((desc, function) -> {
            try {
                long start = System.currentTimeMillis();
                function.invoke();
                log.info("ApplicationInit {}.costTime {} ms", desc, System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("ApplicationInit {}.error", desc, e);
            }
        });
    }

    private void initFastJson() {
        SkuDO skuDO = new SkuDO();
        skuDO.setSkuId(1L);
        skuDO.setSkuName("苹果");
        String jsonString = JSON.toJSONString(skuDO);
        System.out.println(jsonString);
        SkuDO sku = JSON.parseObject(jsonString, SkuDO.class);
    }

    interface InitFunction {

        void invoke();
    }
}
